import json
import datetime
import numpy as np
import pandas as pd
import plotly.express as px
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from dash.exceptions import PreventUpdate
import dash_bootstrap_components as dbc
india_states = json.load(open(r"C:\Users\Asus\Desktop\New folder\states_india.geojson",'r'))
state_id_map = {}
for feature in india_states["features"]:
feature["id"] = feature["properties"]["state_code"]
state_id_map[feature["properties"]["st_nm"]] = feature["id"]
state_id_map
{'Telangana': 0,
'Andaman & Nicobar Island': 35,
'Andhra Pradesh': 28,
'Arunanchal Pradesh': 12,
'Assam': 18,
'Bihar': 10,
'Chhattisgarh': 22,
'Daman & Diu': 25,
'Goa': 30,
'Gujarat': 24,
'Haryana': 6,
'Himachal Pradesh': 2,
'Jammu & Kashmir': 1,
'Jharkhand': 20,
'Karnataka': 29,
'Kerala': 32,
'Lakshadweep': 31,
'Madhya Pradesh': 23,
'Maharashtra': 27,
'Manipur': 14,
'Chandigarh': 4,
'Puducherry': 34,
'Punjab': 3,
'Rajasthan': 8,
'Sikkim': 11,
'Tamil Nadu': 33,
'Tripura': 16,
'Uttar Pradesh': 9,
'Uttarakhand': 5,
'West Bengal': 19,
'Odisha': 21,
'Dadara & Nagar Havelli': 26,
'Meghalaya': 17,
'Mizoram': 15,
'Nagaland': 13,
'NCT of Delhi': 7}
df=pd.read_csv(r'E:\ml\covid-19-india-data-master\covid-19-india-data-master\state_wise (1) all.csv')
df["id"] = df["State"].apply(lambda x: state_id_map[x])
df.head()
| State | Confirmed | Recovered | Deaths | Active | Last_Updated_Time | id | |
|---|---|---|---|---|---|---|---|
| 0 | Maharashtra | 671942 | 480114 | 21995 | 169516 | 22-08-2020 19:57 | 27 |
| 1 | Tamil Nadu | 373410 | 313280 | 6420 | 53710 | 22-08-2020 20:26 | 33 |
| 2 | Andhra Pradesh | 345216 | 252638 | 3189 | 89389 | 22-08-2020 18:29 | 28 |
| 3 | Karnataka | 271876 | 184568 | 4615 | 82677 | 22-08-2020 20:52 | 29 |
| 4 | NCT of Delhi | 160016 | 144138 | 4284 | 11594 | 22-08-2020 18:29 | 7 |
fig = px.choropleth(
df,
locations="id",
geojson=india_states,
color="Confirmed",
hover_name="State",
hover_data=["Confirmed","Recovered","Deaths","Confirmed","Last_Updated_Time"],
title="Covid-19 india",
)
fig.update_geos(fitbounds="locations", visible=False)
fig.show()
fig = px.choropleth_mapbox(
df,
locations="id",
geojson=india_states,
color="Confirmed",
hover_name="State",
hover_data=["Confirmed","Recovered","Deaths","Active","Last_Updated_Time"],
title="Covid-19 india",
mapbox_style="carto-positron",
center={"lat": 24, "lon": 78},
zoom=3,
opacity=0.5
)
fig.update_geos(fitbounds="locations", visible=False)
fig.show()
px.scatter(df[df['Confirmed']>10000],
x='Confirmed', y='Deaths',
color='State', size='Confirmed',
text='State',
log_x =True, log_y=True,
title='Confirmed vs Death (Only States with more thatn 10000 cases)')
fig = px.bar(df.sort_values("Confirmed"),
x='State', y="Confirmed",
hover_name="State",
hover_data=["Confirmed","Last_Updated_Time"],
color="Confirmed",
title='COVID-19:Confirmed cases',
)
fig.update_xaxes(title_text="State")
fig.show()
fig = px.bar(df.sort_values("Recovered"),
x='State', y="Recovered",
hover_name="State",
hover_data=["Recovered","Last_Updated_Time"],
color="Recovered",
title='COVID-19:Recovered cases',
)
fig.update_xaxes(title_text="State")
fig.show()
fig = px.bar(df.sort_values("Deaths"),
x='State', y="Deaths",
hover_name="State",
hover_data=["Deaths","Last_Updated_Time"],
color="Deaths",
title='COVID-19:Deaths',
)
fig.update_xaxes(title_text="State")
fig.show()
fig = px.bar(df.sort_values("Active"),
x='State', y="Active",
hover_name="State",
hover_data=["Active","Last_Updated_Time"],
color="Active",
title='COVID-19:Active cases',
)
fig.update_xaxes(title_text="State")
fig.show()
fig = px.treemap(df, path=["State"], values="Confirmed",
height=700,
title='Number of Confirmed Cases',
hover_data=["Confirmed","Recovered","Deaths","Active","Last_Updated_Time"],
color_discrete_sequence = px.colors.qualitative.Vivid)
fig.data[0].textinfo = 'label+text+value'
fig.show()
CONFIRMED = pd.read_csv(r'E:\ml\covid-19-india-data-master\covid-19-india-data-master\Confirmed.csv')
DEATHS = pd.read_csv(r'E:\ml\covid-19-india-data-master\covid-19-india-data-master\Deaths.csv')
RECOVERED = pd.read_csv(r'E:\ml\covid-19-india-data-master\covid-19-india-data-master\Recovered.csv')
def process_data(data,State='Maharastra',window=3):
CONFIRMED = data
CONFIRMED_State = CONFIRMED[CONFIRMED['States']==State]
final_dataset = CONFIRMED_State.T[4:].sum(axis='columns').diff().rolling(window=window).mean()[70:]
df = pd.DataFrame(final_dataset,columns=['Total'])
return df
def get_overall_total(df):
return df.iloc[:,-1].sum()
CONFIRMED_overall_total = get_overall_total(CONFIRMED)
DEATHS_overall_total = get_overall_total(DEATHS)
RECOVERED_overall_total = get_overall_total(RECOVERED)
print('Total Confirmed:',CONFIRMED_overall_total)
print('Total Deaths:',DEATHS_overall_total)
print('Total Recovered:',RECOVERED_overall_total)
Total Confirmed: 3042888 Total Deaths: 113604 Total Recovered: 2272889
def get_State_total(df,State='Maharashtra'):
return df[df['States']==State].iloc[:,-1].sum()
State = 'Maharashtra'
CONFIRMED_State_total = get_State_total(CONFIRMED,State)
DEATHS_State_total = get_State_total(DEATHS,State)
RECOVERED_State_total = get_State_total(RECOVERED,State)
print(f'{State} Confirmed:',CONFIRMED_State_total)
print(f'{State} Deaths:',DEATHS_State_total )
print(f'{State} Recovered:',RECOVERED_State_total)
Maharashtra Confirmed: 671942 Maharashtra Deaths: 21994 Maharashtra Recovered: 480114
def fig_Country_trend(State='Maharashtra',window=3):
df = process_data(data=CONFIRMED,State=State,window=window)
df.head(10)
if window==1:
yaxis_title = "Daily Cases"
else:
yaxis_title = "Daily Cases ({}-day MA)".format(window)
fig = px.line(df, y='Total', x=df.index, title='Daily confirmed cases trend for {}'.format(State),height=600,color_discrete_sequence =['RED'])
fig.update_layout(font_color="white",title_x=0.5,plot_bgcolor='#222222',paper_bgcolor='#222222',xaxis_title="Date",yaxis_title=yaxis_title)
return fig
external_stylesheets = [dbc.themes.BOOTSTRAP]
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.title = 'Covid-19 India Dashboard'
colors = {
'background':'#171717 ',
'bodyColor':'#222222',
'text': '#FDFEFE '
}
def get_page_heading_style():
return {'backgroundColor': colors['background']}
def get_page_heading_title():
return html.H1(children='COVID-19 India Dashboard',
style={
'textAlign': 'center',
'color': colors['text']
})
def get_page_heading_subtitle():
return html.Div(children='Visualize Covid-19 India data generated from sources all over the world.',
style={
'textAlign':'center',
'color':colors['text']
})
def generate_page_header():
main_header = dbc.Row(
[
dbc.Col(get_page_heading_title(),md=12)
],
align="center",
style=get_page_heading_style()
)
subtitle_header = dbc.Row(
[
dbc.Col(get_page_heading_subtitle(),md=12)
],
align="center",
style=get_page_heading_style()
)
header = (main_header,subtitle_header)
return header
def get_State_list():
return CONFIRMED['States'].unique()
def create_dropdown_list(State_list):
dropdown_list = []
for State in sorted(State_list):
tmp_dict = {'label':State,'value':State}
dropdown_list.append(tmp_dict)
return dropdown_list
def get_State_dropdown(id):
return html.Div([
html.Label('Select State'),
dcc.Dropdown(id='my-id'+str(id),
options=create_dropdown_list(get_State_list()),
value='Maharashtra'
),
html.Div(id='my-div'+str(id))
])
def graph1():
return dcc.Graph(id='graph1',figure=fig_Country_trend('Maharashtra'))
def generate_card_content(card_header,card_value,overall_value):
card_head_style = {'textAlign':'center','fontSize':'150%'}
card_body_style = {'textAlign':'center','fontSize':'200%'}
card_header = dbc.CardHeader(card_header,style=card_head_style)
card_body = dbc.CardBody(
[
html.H5(f"{int(card_value):,}", className="card-title",style=card_body_style),
html.P(
"Country Wide: {:,}".format(overall_value),
className="card-text",style={'textAlign':'center'}
),
]
)
card = [card_header,card_body]
return card
def generate_cards(State='Maharashtra'):
CONFIRMED_State_total = get_State_total(CONFIRMED,State)
DEATHS_State_total = get_State_total(DEATHS,State)
RECOVERED_State_total = get_State_total(RECOVERED,State)
cards = html.Div(
[
dbc.Row(
[
dbc.Col(dbc.Card(generate_card_content("Recovered", RECOVERED_State_total, RECOVERED_overall_total), color="success", inverse=True),md=dict(size=2,offset=3)),
dbc.Col(dbc.Card(generate_card_content("Confirmed",CONFIRMED_State_total,CONFIRMED_overall_total), color="warning", inverse=True),md=dict(size=2)),
dbc.Col(dbc.Card(generate_card_content("Dead",DEATHS_State_total,DEATHS_overall_total),color="danger", inverse=True),md=dict(size=2)),
],
className="mb-4",
),
],id='card1'
)
return cards
def get_slider():
return html.Div([
dcc.Slider(
id='my-slider',
min=1,
max=15,
step=None,
marks={
1: '1',
3: '3',
5: '5',
7: '1-Week',
},
value=3,
),
html.Div([html.Label('Select Moving Average Window')],id='my-div'+str(id),style={'textAlign':'center'})
])
def generate_layout():
page_header = generate_page_header()
layout = dbc.Container(
[
page_header[0],
page_header[1],
html.Hr(),
generate_cards(),
html.Hr(),
dbc.Row(
[
dbc.Col(get_State_dropdown(id=1),md=dict(size=4,offset=4))
]
),
dbc.Row(
[
dbc.Col(graph1(),md=dict(size=6,offset=3))
],
align="center",
),
dbc.Row(
[
dbc.Col(get_slider(),md=dict(size=4,offset=4))
]
),
],fluid=True,style={'backgroundColor': colors['bodyColor']}
)
return layout
app.layout = generate_layout()
@app.callback(
[Output(component_id='graph1',component_property='figure'), #line chart
Output(component_id='card1',component_property='children')], #overall card numbers
[Input(component_id='my-id1',component_property='value'), #dropdown
Input(component_id='my-slider',component_property='value')] #slider
)
def update_output_div(input_value1,input_value2):
return fig_Country_trend(input_value1,input_value2),generate_cards(input_value1)
app.run_server(host='127.0.0.1')
Dash is running on http://127.0.0.1:8050/ * Serving Flask app "__main__" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: off
* Running on http://127.0.0.1:8050/ (Press CTRL+C to quit)